package org.joinme.backend.controller;

import com.alibaba.fastjson.JSONObject;
import org.joinme.backend.model.WechatUser;
import org.joinme.backend.service.WechatUserService;
import org.joinme.backend.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = {"/{appName}/wechat/user"}, produces = {"application/json;charset=UTF-8"})
public class WechatUserController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatUserService userService;

    //用户登录
    @ResponseBody
    @RequestMapping("/login/code")
    public String userLogin(HttpServletRequest request, String code, WechatUser user, @PathVariable String appName){
        try {
            request.setCharacterEncoding("UTF-8");
            if(StringUtil.isEmpty(code))
                throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_CODE_ERROR);

            if (userService.userWechatLogin(request, code, user, appName)) {
                JSONObject sessionId = new JSONObject();
                sessionId.put("sessionId", request.getSession().getId());

                return ApiResult.writeData(sessionId);
            } else {
                throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_FAIL);
            }
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/get")
    public String getLoginUserWechat(HttpServletRequest request){
        try {
            return ApiResult.writeData(userService.getLoginUserWechat(request));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/getSpecific")
    public String getSpecificWechatUser(HttpServletRequest request, @RequestParam int userId){
        try {
            if(userId == -1)
                userId = userService.getLoginUserId(request);
            return ApiResult.writeData(userService.getSpecificWechatUser(userId));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/update")
    public String updateUserWechat(HttpServletRequest request, WechatUser user){
        try {
            int userId = userService.getLoginUserId(request);
            user.setUserId(userId);

            if(userService.updateUserWechat(user))
                return ApiResult.SUCCESS;
            else
                throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_CODE_ERROR);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    @ResponseBody
    @RequestMapping("/login/session")
    public String userLoginEnforce(HttpServletRequest request, @PathVariable String appName, String userInfo){
        try {
            if(StringUtil.isEmpty(userInfo))
                throw new PrjException(ErrorCodeMsg.SYSTEM_ERROR);

            System.out.println("appName : " + appName);

            request.getSession().setAttribute("userInfo", userInfo);

            JSONObject sessionId = new JSONObject();
            sessionId.put("sessionId", request.getSession().getId());

            return ApiResult.writeData(sessionId);
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
}
